var express = require('express');
var router = express.Router();

//引入配置和数据库操作
const {
    API_URL,
    verifyToken
} = require('../utils/config')
const Query = require('../utils/db')
const timestamp = require('time-stamp')

//引入文件上传的包
const fs = require('fs');
const path = require('path')
const formidable = require('formidable');
const {
    v4: uuidv4
} = require('uuid')

//中间件 必须有token的才能登录
router.use('/', (req, res, next) => {
    // let token = req.headers.authorization
    // if (!verifyToken(token)) {
    //     res.send('请登录')
    //     return
    // }
    next();
})

//获取视频信息
router.get('/api/video', async (req, res, next) => {
    let {
        id = ''
    } = req.query;
    if (id == '') {
        next({
            msg: "请传递必要参数",
        })
        return;
    }
    let {
        result: [result]
    } = await Query(`select concat('${API_URL}/uploads/videos/',video_src) as video_src,video_title from e_video where id = ${id}`)
    next({
        status: 200,
        result,
    })
})

//报名课程
router.post('/api/study', async (req, res, next) => {
    let {
        cid = '', mid = ''
    } = req.body;
    if (cid == '' || mid == '') {
        next({
            msg: "请传递必要参数",
        })
        return;
    }

    let {
        result
    } = await Query(`select * from e_order where cid = '${cid}' and mid = '${mid}'`)

    if (result.length > 0) {
        next({
            msg: "已经报名此课程"
        })
        return;
    }
    let oid = timestamp('YYYYMMDDHHmmss') + (Math.random() + '').substr(2, 6);
    let createdate = Date.now();
    let {
        result: result1
    } = await Query(`insert into e_order (oid,cid,mid,createdate,status) values ('${oid}','${cid}','${mid}','${createdate}',1) `)
    if (result1.affectedRows > 0) {
        next({
            status: 200,
        })
    }
    next({
        msg: "请稍后再试"
    })

})

//获取用户信息
router.get('/api/user', async (req, res, next) => {
    let {
        mid = ''
    } = req.query;
    if (mid == '') {
        next({
            "msg": "请传递必要参数",
        })
        return;
    }
    let sql = `select id,mid,realname,username,sex,birthdate,city,concat('${API_URL}','/uploads/head_photo/',head_photo_url) as head_photo_url,createdate from e_member where mid = '${mid}' `
    let {
        result,
    } = await Query(sql)

    if (result.length == 0) {
        next({
            msg: "查无此人",
        })
        return;
    }
    next({
        status: 200,
        result: result[0]
    })
})

//更新用户头像
router.post('/api/uploadhead', async (req, res, next) => {
    const form = formidable({
        uploadDir: path.join(__dirname, '../uploads/head_photo'), //上传的指定目录地址,最好用绝对地址
    })

    //接收表单传递过来的数据
    form.parse(req, async (err, fields, files) => {
        console.log(fields, '普通的表单数据');
        console.log(files, '文件数据');
        let mid = fields.mid;
        //在这里进行重命名。
        let suffixName = path.extname(files.f.name) //后缀名
        let f = uuidv4() + suffixName // 新文件名
        let newPath = path.join(__dirname, '../uploads/head_photo', f)
        //2. 获取以前路径名
        let oldpath = files.f.path
        //3. 重命名
        fs.renameSync(oldpath, newPath)

        if (mid == '' || f == '') {
            next({
                msg: "请传递必要参数",
            })
            return;
        }

        let sql = `update e_member set head_photo_url = '${f}' where mid = '${mid}' `
        let {
            result
        } = await Query(sql);
        if (result.affectedRows == 0) {
            next({
                msg: "更新失败",
            })
            return;
        }
        next({
            status: 200,
            result: API_URL + '/uploads/head_photo/' + f, //返回上传的头像
        })
    })
})

//更新用户信息
router.put('/api/user', async (req, res, next) => {
    let {
        realname = '', sex = 1, birthdate = '', city = '', mid = ''
    } = req.body;
    if (realname == '' || sex == '' || birthdate == '' || city == '' || mid == '') {
        next({
            msg: "请传递必要参数",
        })
        return;
    }
    let sql = `update e_member set realname = '${realname}',sex ='${sex}',birthdate = '${birthdate}',city = '${city}' where mid = '${mid}' `
    let {
        result,
    } = await Query(sql)

    if (result.affectedRows == 0) {
        next({
            msg: "查无此人",
        })
        return;
    }
    next({
        msg: "OK",
        status: 200,
    })
})

//获取学习记录
router.get('/api/orders', async (req, res, next) => {
    let {
        mid = ''
    } = req.query;
    if (mid == '') {
        next({
            msg: "请传递必要参数",
        })
        return;
    }
    let sql = ` select oid,title,price,subject_name,area_name,createdate from e_course join e_order on e_course.cid = e_order.cid where e_order.mid = '${mid}' `

    let {
        result,
    } = await Query(sql)

    if (result.length == 0) {
        next({
            msg: "查无此人",
        })
        return;
    }
    next({
        status: 200,
        result,
        // a: verifyToken(token)
    })
})


module.exports = router;